<template>
  <div class="reviews-container">
    <!-- 加载中状态 -->
    <div v-if="loading" class="loading-container">
      <div class="skeleton-card" v-for="i in 4" :key="i"></div>
    </div>
    <div v-else-if="reviews.length === 0" class="no-reviews">
      <div class="no-reviews-icon">
        <svg
          width="40"
          height="40"
          viewBox="0 0 24 24"
          fill="none"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z"
            stroke="#999"
            stroke-width="2"
          />
          <path
            d="M8 14C8 14 9.5 16 12 16C14.5 16 16 14 16 14M9 9H9.01M15 9H15.01"
            stroke="#999"
            stroke-width="2"
            stroke-linecap="round"
          />
        </svg>
      </div>
      <div class="no-reviews-text">
        There are no reviews for the selected period/source, please reset the
        filter and try again
      </div>
    </div>
    <!-- 评论卡片列表 -->
    <div v-else ref="reviewList" class="review-list">
      <div
        v-for="(review, index) in reviews"
        :key="review.reviewId || index"
        class="review-card"
      >
        <!-- 评论卡片内容保持不变 -->
        <div class="review-header">
          <div class="platform-logo">
            <img
              :src="getPlatformLogo(review.source)"
              :alt="review.source + ' logo'"
            />
          </div>
          <span class="platform-name">{{
            formatPlatformName(review.source)
          }}</span>
          <div class="rating-score">
            {{ getFormattedRating(review.overallPointFromOTA, review.source) }}
          </div>
          <div class="reviewer-info">
            <div
              style="
                font-family: 'Inter Variable', sans-serif;
                font-size: 0.1111rem;
              "
            >
              {{ getCountryOnly(review.userLocation) || "" }}
            </div>
            <div class="country-flag" v-if="review.userLocation">
              <img
                :src="getCountryFlag(review.userLocation)"
                :alt="review.userLocation + ' flag'"
              />
            </div>
          </div>
        </div>

        <div class="review-body">
          <div
            class="sentiment-score-container"
            @mouseenter="showTooltip = index"
            @mouseleave="showTooltip = null"
          >
            <div
              class="sentiment-score"
              :class="getSentimentClass(review.sentimentAnalysis.overall_score)"
            >
              {{ review.sentimentAnalysis.overall_score || "N/A" }}
            </div>
            <div v-if="showTooltip === index" class="sentiment-tooltip">
              <div
                style="
                  font-size: 0.1111rem;
                  font-weight: 600;
                  font-family: 'Inter Variable', sans-serif;
                "
              >
                Natural Language Processing (NLP) score:
              </div>
              <div
                style="
                  color: #6a6969;
                  margin-top: 10px;
                  font-size: 0.0972rem;
                  font-family: 'Inter Variable', sans-serif;
                "
              >
                <div>Calculated based on advanced AI sentiment analysis</div>
                <div>and contributions from hotel experts</div>
              </div>
            </div>
          </div>
          <div class="review-content" :class="{ 'ai-expanded': showAi[index] }">
            <div
              class="review-form"
              :class="getBorderClass(review.sentimentAnalysis.overall_score)"
            >
              <ReviewFormPlatform
                @sentiment-point="handleSentimentPoint"
                @replyClick="
                  () => {
                    toggleAiDisplay(index);
                    isReplyClicked[index] = true;
                  }
                "
                :collapsed="showAi[index]"
                :review="review"
                :is-reply-expanded="showAi[index]"
              />
            </div>
            <div v-if="showAi[index]" class="ai-assistant">
              <Ai
                :left-content-height="leftContentHeight"
                :left-buttons-height="leftButtonsHeight"
                :review="review"
                :show-reply="showAi[index]"
              />
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-container" v-if="!loading && reviews.length > 0">
      <el-pagination
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import ReviewFormPlatform from "./ReviewFormPlatform.vue";
import Ai from "./Ai.vue";

export default {
  name: "MultiInfoReviewCard",
  components: {
    ReviewFormPlatform,
    Ai,
  },
  props: {
    reviews: {
      type: Array,
      default: () => [],
    },
    isLoading: {
      type: Boolean,
      default: true,
    },
    currentPage: {
      type: Number,
      default: 1,
    },
    pageSize: {
      type: Number,
      default: 10,
    },
    total: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      showAi: Array(4).fill(false),
      showTooltip: null,
      sentimentPoint: null,
      source: "",
      userLocation: "",
      overallPointFromOTA: "",
      loading: false,
      leftContentHeight: 0,
      leftButtonsHeight: 0,
      isReplyClicked: [], // 新增：记录每个评论是否点击过Reply按钮
    };
  },
  mounted() {
    // 初始化每个评论的"是否点击Reply"状态为false
    this.isReplyClicked = new Array(this.reviews.length).fill(false);
  },
  watch: {
    isLoading(newVal) {
      this.loading = newVal;
    },
    // 监听评论数据变化，当数据更新时重置展开状态
    reviews: {
      handler() {
        this.resetReplyStates();
      },
      deep: true, // 深度监听，确保对象内部变化也能触发
    },
  },
  methods: {
    // 重置所有Reply的展开状态
    resetReplyStates() {
      this.showAi = this.reviews.map(() => false);
      this.isReplyClicked = this.reviews.map(() => false);
    },
    // 切换单个评论的Reply展开状态
    toggleAiDisplay(index) {
      this.showAi[index] = !this.showAi[index];
      this.isReplyClicked[index] = true;
    },
    handlePageChange(page) {
      this.showAi = {};
      this.$emit("page-change", page);
    },
    getCountryOnly(location) {
      if (!location) return "";

      // 添加常见国家名称到缩写的映射
      const countryMappings = {
        "United Kingdom": "UK",
        "United States": "USA",
        "United States of America": "USA",
        "People's Republic of China": "China",
        "Republic of Korea": "Korea",
        // 可以继续添加其他需要映射的国家名称
      };

      // 先检查是否存在完整国家名的映射
      const normalizedLocation = location.trim();
      if (countryMappings[normalizedLocation]) {
        return countryMappings[normalizedLocation];
      }

      // 如果没有映射，则按原逻辑处理
      const parts = location.split(",");
      return parts[parts.length - 1].trim();
    },
    // formatPlatformName(source) {
    //   if (!source) return "";
    //   // 可补充特殊平台的映射（如之前需求中的BOOKING→Booking.com）
    //   const platformMap = {
    //     BOOKING: "Booking.com",
    //     TRIP: "Ctrip.com",
    //   };
    //   return (
    //     platformMap[source] ||
    //     source.charAt(0).toUpperCase() + source.slice(1).toLowerCase()
    //   );
    // },
    formatPlatformName(source) {
      if (!source) return ""; // 处理空值，返回空字符串
      // 首字母大写 + 剩余部分转为小写
      return source.charAt(0).toUpperCase() + source.slice(1).toLowerCase();
    },
    getFormattedRating(overallPointFromOTA, source) {
      if (!overallPointFromOTA) return "N/A";
      const platform = source.toLowerCase();
      const isFiveStarScale =
        platform.includes("google") || platform.includes("tripadvisor");
      const rating = parseFloat(overallPointFromOTA);
      return isFiveStarScale
        ? `${rating.toFixed(1)} / 5`
        : `${overallPointFromOTA} / 10`;
    },
    getCountryFlag(location) {
      if (!location) return require("@/assets/reply/default-flag.png");
      const COUNTRY_MAPPINGS = {
        germany: "germany",
        deutschland: "germany",
        de: "germany",
        uk: "uk",
        "united kingdom": "uk",
        usa: "usa",
        "united states": "usa",
        us: "usa",
        italy: "italy",
      };
      try {
        const normalized = location.trim().toLowerCase();
        let country = normalized.split(",").pop().trim();
        country = country.replace(/[^a-z]/g, "");
        const fileName =
          COUNTRY_MAPPINGS[country] || COUNTRY_MAPPINGS[normalized] || country;
        return require(`@/assets/reply/${fileName}.png`);
      } catch (e) {
        console.error(`Flag load error: ${location}`, e);
        return require("@/assets/reply/default-flag.png");
      }
    },
    getPlatformLogo(source) {
      const platformName = source.toLowerCase().replace(/[^a-z0-9]/g, "");
      try {
        return require(`@/assets/reply/${platformName}.png`);
      } catch (e) {
        return "";
      }
    },
    toggleAiDisplay(index) {
      this.$set(this.showAi, index, !this.showAi[index]);
    },
    handleSentimentPoint(point, source, userLocation, overallPointFromOTA) {
      this.sentimentPoint = parseFloat(point);
      this.source = source;
      this.userLocation = userLocation;
      this.overallPointFromOTA = overallPointFromOTA;
    },
    getBorderClass(score) {
      if (score === null || score === undefined) return "border-none";
      if (score >= 9) return "border-success";
      if (score < 5) return "border-danger";
      return "border-neutral";
    },
    getSentimentClass(score) {
      if (score == 0) return "score-na";
      if (score >= 9) return "score-deep-green";
      if (score >= 8) return "score-green";
      if (score >= 7) return "score-yellow";
      if (score >= 5) return "score-orange";
      if (score >= 3) return "score-red";
      if (score >= 1) return "score-deep-red";
      return "";
    },
  },
};
</script>

<style scoped lang="scss">
.reviews-container {
  // margin-top: 40px;
  display: flex;
  flex-direction: column;
  gap: 40px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.skeleton-card {
  display: flex;
  flex-direction: column;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
  gap: 20px;
  position: relative;
  overflow: hidden;
}

.skeleton-card::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s infinite;
  z-index: 1;
  opacity: 0.6;
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.review-card {
  display: flex;
  flex-direction: column;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 16px;
  gap: 20px;
  margin-block: 20px;
}

.review-header {
  display: flex;
  align-items: center;

  .platform-logo {
    margin-right: 24px;
    width: 0.1944rem;
    height: 0.1944rem;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .platform-name {
    font-weight: 700;
    font-size: 0.1389rem;
    color: #454545;
  }

  .rating-score {
    margin-left: 10px;
    font-size: 0.125rem;
    font-weight: 600;
  }

  .reviewer-info {
    margin-left: 25px;
    display: flex;
    align-items: center;

    .country-flag {
      margin-left: 8px;
      width: 0.1389rem;
      height: 0.1389rem;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.review-body {
  display: flex;
  gap: 20px;

  .sentiment-score-container {
    position: relative;
    width: 35px;
  }

  .sentiment-score {
    display: flex;
    justify-content: center;
    font-size: 0.1528rem;
    font-weight: 700;
    padding-top: 24px;
    width: 35px;
    cursor: url("@/assets/cursor.png"), auto;
    &:hover {
      opacity: 0.8; // 鼠标悬停时透明度变为80%
      transform: scale(1.05); // 轻微放大效果（可选）
    }
    &.score-deep-green {
      color: #006400;
    }
    &.score-green {
      color: #2faa68;
    }
    &.score-yellow {
      color: #ffcc00;
    }
    &.score-orange {
      color: #f68d2b;
    }
    &.score-red {
      color: #e51837;
    }
    &.score-deep-red {
      color: #8b0000;
    }
    &.score-na {
      color: #6a6969;
      font-size: 0.0972rem;
      font-weight: 500;
    }
  }

  .sentiment-tooltip {
    position: absolute;
    top: 12%;
    left: 0;
    transform: none;
    background-color: #fff;
    color: #000;
    padding: 8px 12px;
    border-radius: 8px;
    font-size: 0.0833rem;
    font-weight: normal;
    white-space: nowrap;
    z-index: 9999;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    border: 1px solid #ccc;
    min-width: 200px;

    &::before {
      content: "";
      position: absolute;
      top: -5px;
      left: 10px;
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-bottom: 5px solid #ccc;
    }
  }

  .review-content {
    display: flex;
    flex-direction: column;
    width: 100%;

    &.ai-expanded {
      flex-direction: row;
      gap: 20px;

      .review-form,
      .ai-assistant {
        flex: 1;
        min-width: 0;
      }
    }
  }

  .review-form {
    border: 3.5px solid transparent;
    border-radius: 12px;

    &.border-success {
      border-color: #2faa68;
    }
    &.border-danger {
      border-color: #db362c;
    }
    &.border-neutral {
      border-color: #f0f0f0;
      border: 2px solid #f0f0f0;
    }
    &.border-none {
      border-color: transparent;
    }
  }

  .ai-assistant {
    border: 1px solid #cdcccc;
    border-radius: 12px;
  }
}

.no-reviews {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;

  .no-reviews-icon {
    margin-bottom: 16px;
  }

  .no-reviews-text {
    font-size: 0.1111rem;
    font-weight: 500;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  padding: 0.1389rem 0;
  background: #fff;
  border-radius: 8px;
}

// 修正分页样式：直接命中所有子元素
::v-deep .el-pagination {
  // 分页组件内所有文本的字体
  font-family: "Inter Variable", sans-serif;

  // 页码按钮样式
  .el-pager li {
    font-size: 0.0972rem !important; // 页码字体大小
    margin: 0 5px; // 页码间距
  }

  // 上一页/下一页按钮样式
  .btn-prev,
  .btn-next {
    font-size: 0.0833rem !important; // 按钮字体大小
  }

  // 其他元素（如总条数、跳转输入框）
  span {
    font-size: 0.0972rem !important;
  }
}
</style>
